package com.zz.tijian.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.tijian.entity.Reply;
import com.zz.tijian.entity.req.AddReplyDto;
import com.zz.tijian.entity.req.CurrentUserInfo;
import com.zz.tijian.entity.res.ReplyVo;
import com.zz.tijian.entity.res.Result;
import com.zz.tijian.mapper.ReplyMapper;
import com.zz.tijian.service.ReplyService;
import com.zz.tijian.utils.UserContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 86137
* @description 针对表【reply】的数据库操作Service实现
* @createDate 2024-06-24 16:14:35
*/
@Service
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, Reply>
    implements ReplyService {


    public List<Reply> findRepliesByTopicId(Integer topicId) {
        LambdaQueryWrapper<Reply> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Reply::getTopicId,topicId);
        return this.list(queryWrapper);
    }
    @Override
    public Result<List<ReplyVo>> buildReplyTree(Integer topicId) {
        List<Reply> replies = this.findRepliesByTopicId(topicId);
        Map<Integer, List<ReplyVo>> replyMap = replies.stream()
                .map(reply -> {
                    ReplyVo replyVo = new ReplyVo();
                    replyVo.setId(reply.getId());
                    replyVo.setTopicId(reply.getTopicId());
                    replyVo.setContent(reply.getContent());
                    replyVo.setUserId(reply.getUserId());
                    replyVo.setRealName(reply.getRealName());
                    replyVo.setCreatedTime(reply.getCreatedTime());
                    replyVo.setParentId(reply.getParentId());
                    return replyVo;
                })
                .collect(Collectors.groupingBy(ReplyVo::getParentId));

        replyMap.values().forEach(replyVos ->
                replyVos.forEach(replyVo ->
                        replyVo.setReplies(replyMap.get(replyVo.getId()))));
        List<ReplyVo> orDefault = replyMap.getOrDefault(0, List.of());
        return Result.ok(orDefault);
    }

    @Override
    public Result<Boolean> addReply(AddReplyDto addReplyDto) {
        CurrentUserInfo currentUserInfo = UserContext.currentUser();
        Reply reply = new Reply();
        BeanUtils.copyProperties(addReplyDto,reply);
        reply.setUserId(currentUserInfo.getUserId());
        reply.setRealName(currentUserInfo.getRealName());
        this.save(reply);
        return Result.ok(true);
    }
}




